package com.andy.basics;

import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;

/**
 * Converts an empty string to null
 * 
 * @author Anand Kumar
 * 
 */
public class EmptyToNullConverter implements javax.faces.convert.Converter {

	private static final String CLASS = EmptyToNullConverter.class.getName();

	private static final Logger DEBUG = Logger.getLogger(Constants.DEBUG_KEY + EmptyToNullConverter.CLASS);

	public EmptyToNullConverter() {
		EmptyToNullConverter.DEBUG.debug(EmptyToNullConverter.CLASS + " instantiated");
	}

	public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
		if ((value == null) || (value.trim().length() == 0)) {
			if (EmptyToNullConverter.DEBUG.isDebugEnabled()) {
				EmptyToNullConverter.DEBUG.debug("Entered string is empty ");
			}
			if (component instanceof EditableValueHolder) {
				EmptyToNullConverter.DEBUG.debug("Component is EditableValueHolder");
				((EditableValueHolder) component).setSubmittedValue(null);
			}
			return null;
		}
		return value;
	}

	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		return (value == null) ? null : value.toString();
	}

}